package com.xncoding.websocket.WebMvc.demo0.config;

import com.xncoding.websocket.WebMvc.demo0.handler.ServletWebSocketServerHandler;
import com.xncoding.websocket.WebMvc.demo0.interceptor.ServletWebSocketHandshakeInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;

/**
 * WebSocketConfig
 *
 * @author XiongNeng
 * @version 1.0
 * @since 2018/3/22
 */
@Configuration
@EnableWebSocket
public class ServletWebSocketServerConfigurer implements WebSocketConfigurer {
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    /*    if (registry instanceof ServletWebSocketHandlerRegistry) {
            //替换UrlPathHelper
            ((ServletWebSocketHandlerRegistry) registry)
                    .setUrlPathHelper(new PrefixUrlPathHelper("/webmvcsocket"));
        }
        registry
                //添加处理器到对应的路径
                .addHandler(new ServletWebSocketServerHandler(), "/webmvcsocket")
                //添加握手拦截器
                .addInterceptors(new ServletWebSocketHandshakeInterceptor())
                .setAllowedOrigins("*");*/
        registry
                //添加处理器到对应的路径
                .addHandler(new ServletWebSocketServerHandler(), "/webmvcsocket/**")
                //添加握手拦截器
                .addInterceptors(new ServletWebSocketHandshakeInterceptor())
                .setAllowedOrigins("*");
    }

    public class PrefixUrlPathHelper extends UrlPathHelper {

        private String prefix;

        public PrefixUrlPathHelper(String prefix) {
            this.prefix = prefix;
        }

        @Override
        public @NonNull String resolveAndCacheLookupPath(@NonNull HttpServletRequest request) {
            //获得原本的Path
            String path = super.resolveAndCacheLookupPath(request);
            //如果是指定前缀就返回对应的通配路径
            if (path.startsWith(prefix)) {
                return prefix + "/**";
            }
            return path;
        }
    }

}
